<div class='container' ng-controller="DemoCtrl">
  <div class='row'>
    <div class='col-md-3'>
      <form class='well'>
    		{{# controls }}
        <label><b>{{label}}</b></label>
    		<select class='form-control' ng-model="opts.{{name}}" 
          ng-options="ctl for ctl in controls.{{name}}.values">   
    		</select><br>
				{{/ controls }}
        {{# hasFilter }}
        <select
          ng-model="selected" 
          ng-options="c as c.value group by c.variable for c in filters" 
          class="form-control" multiple size="10">
        </select>
        {{/ hasFilter }}
      </form>
    </div>
    <div class='col-md-8'>
      <div class="bs-docs-example">
        <div id='{{chartId}}' class='rChart {{lib}}'>
          <svg></svg>
        </div>
        {{# CODE }}<pre><code class='r'>{{CODE}}</code></pre>{{/ CODE }}
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
function DemoCtrl($scope){
  $scope.opts = {{{ opts }}}
  $scope.data = {{{ data }}}
  $scope.controls = {{{ controls_json }}} 
  $scope.filters = {{{ filters_json }}}
  
  $scope.drawChart = function(){
    drawChart($scope.opts, $scope.data)  
  }
  
  $scope.$watch('selected', function(){
    var keys = _.pluck($scope.selected, "variable")
    var values = _.pluck($scope.selected, "value")
    $scope.opts.selected = _.zipObject(keys, values)
  }) 
  
  $scope.$watch('opts',function(){
    $scope.drawChart()
	}, true)
}  

function drawChart(opts, data){ 
  if (Object.keys(opts.selected).length > 0){
    data = _.filter(data, opts.selected)
  }
  
  if(!(opts.type==="pieChart" || opts.type==="sparklinePlus" || opts.type==="bulletChart")) {
    var data = d3.nest()
      .key(function(d){
        //return opts.group === undefined ? 'main' : d[opts.group]
        //instead of main would think a better default is opts.x
       return opts.group === undefined ? opts.y : d[opts.group];
      }).entries(data);
  }
      
  if (opts.disabled != undefined){
    data.map(function(d, i){
      d.disabled = opts.disabled[i]
    })
  }
	
	nv.addGraph(function() {
		var chart = nv.models[opts.type]()
			.x(function(d) { return d[opts.x] })
			.y(function(d) { return d[opts.y] })
			.width(opts.width)
			.height(opts.height)
		
	{{{ chart }}}
          
	{{{ xAxis }}}

	{{{ x2Axis }}}
	
	{{{ yAxis }}}

	d3.select("#" + opts.id + ' svg')
  // .empty()
		.datum(data)
		.transition().duration(500)
		.call(chart);
	
	 nv.utils.windowResize(chart.update);
	 return chart;
  });
};
</script>